<template>
  <div v-loading="loading" :element-loading-text="loadingText">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <!--项目回款资金来源-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('分配资金来源') }}</span>
      </div>
      <el-table :data="form.dealIncomeList" border class="formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('回款来源')" align="center" prop="fundIncome.dealName">
          <template slot-scope="scope">
            <span>{{ scope.row.fundIncome.dealName ? scope.row.fundIncome.dealName : typeFeeFormat(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('回款时间')" align="center" prop="holderName">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.fundIncome.distributionDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('来源类型')" align="center" prop="dealType">
          <template slot-scope="scope">
            <span>{{ selectDictLabel(dealTypeOptions, scope.row.fundIncome.dealType) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本金') + $t('金额单位')" align="center" prop="amountPrincipal">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountPrincipal, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('收益') + $t('金额单位')" align="center" prop="amountIncome">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountIncome, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('分红') + $t('金额单位')" align="center" prop="amountBonus">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountBonus, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('其他') + $t('金额单位')" align="center" prop="amountOthers">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountOthers, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('操作')"
          align="center"
          width="80"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              :v-bind:v-has-permi="['company:holder:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="delRowDeal(scope.$index,scope.row)"
            >{{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol" style="margin-bottom: 30px;">
        <el-button size="small" type="primary" @click="addHandle('deal', form.dealIncomeList)">{{ $t("选择") }}</el-button>
      </div>
      <!--其他收益资金来源-->
      <!--      <div class="area-header">
        <span class="area-header-title">{{ $t('其他资金来源') }}</span>
      </div>
      <el-table :data="form.otherIncomeList" border class="formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('回款时间')" align="center" prop="holderName">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.fundIncome.distributionDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本金') + $t('金额单位')" align="center" prop="amountPrincipal">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountPrincipal, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('收益') + $t('金额单位')" align="center" prop="amountIncome">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountIncome, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('分红') + $t('金额单位')" align="center" prop="amountBonus">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountBonus, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('其他') + $t('金额单位')" align="center" prop="amountOthers">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.fundIncome.amountOthers, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('操作')"
          align="center"
          width="80"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="delRowOther(scope.$index,scope.row)"
            >{{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol" style="margin-bottom: 30px;">
        <el-button size="small" type="primary" @click="addHandle('other')">{{ $t("选择") }}
        </el-button>
      </div>-->
      <div>
        <!--基金费用，只查询实际的-->
        <div class="area-header">
          <span class="area-header-title">{{ $t('扣除费用') }}</span>
        </div>
        <el-table :data="form.fundExpenseList" border class="formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('申请标题')" align="center" prop="actTitle" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('申请时间')" align="center" prop="applyTime" show-overflow-tooltip width="110">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.applyTime) }}</span>
            </template>
          </el-table-column>
          <!--<el-table-column label="部门" align="center" prop="departmentName" />-->
          <el-table-column :label="$t('费用金额(元)')" header-align="center" align="right" prop="amountMoney" show-overflow-tooltip width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ moneyFormat(scope.row.amountMoney) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('费用类型')" align="center" prop="typesFee">
            <template slot-scope="scope">
              <span>{{ selectDictLabel(typesFeeOptions, scope.row.typesFee) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('费用明细')" align="center" prop="costsThat" show-overflow-tooltip />
          <el-table-column
            :label="$t('操作')"
            align="center"
            width="80"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="delRowFundExpense(scope.$index,scope.row)"
              >{{ $t('删除') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol" style="margin-bottom: 30px;">
          <el-button size="small" type="primary" @click="addExpenseHandle(form.fundExpenseList)">{{ $t("选择") }}
          </el-button>
        </div>
      </div>

      <div class="area-header">
        <span class="area-header-title">{{ $t('分配基本信息') }}</span>
      </div>
      <el-row>
        <el-col v-if="useProcess" :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input
              v-model="form.actTitle"
              :placeholder="$t('申请标题')"
              show-word-limit
              :maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配批次')" prop="fpQc">
            <el-input v-model="form.fpQc" :placeholder="$t('分配批次')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配类型')" prop="fpType">
            <el-select v-model="form.fpType" multiple :placeholder="$t('分配类型')">
              <el-option
                v-for="dict in fpTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配时间')" prop="fpTime">
            <DatePicker
              v-model="form.fpTime"
              :placeholder="$t('分配时间')"
              @change="getLastFpDetail(form.fpTime)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配资金') + $t('金额单位')" prop="sourceAmount">
            <Money v-model="form.sourceAmount" disabled unit="w" :placeholder="$t('汇总分配资金')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('扣除费用') + $t('金额单位')" prop="deductAmount">
            <Money v-model="form.deductAmount" disabled unit="w" :placeholder="$t('汇总扣除费用')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配预留费用') + $t('金额单位')" prop="reserveAmount">
            <Money v-model="form.reserveAmount" unit="w" :placeholder="$t('分配预留费用')" @change="reserveAmountCal" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分配总金额') + $t('金额单位')" prop="fpTotalAmount">
            <Money v-model="form.fpTotalAmount" unit="w" :placeholder="$t('分配总金额')" @change="moneyValidCustom" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--分配明细-->
      <div class="list-table" style="padding: 0; box-shadow: rgba(218, 223, 232, 0) 0 3px 12px 2px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('出资人分配明细') }}</span>
          <span v-if="moneyEquationFlag" style="color:red;">{{ $t('与分配总金额不相等，相差' + subFpAmount) }}</span>
          <div style="float: right;font-size: 15px;">
            <template>
              <el-radio-group v-model="showFpDetailsType" @change="changeRadio(showFpDetailsType)">
                <el-radio
                  v-for="dict in fundFpCalRuleOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}</el-radio>
              </el-radio-group>
            </template>
          </div>
        </div>
        <div v-if="showFpDetailsType === 'auto'">
          <fund-fp-group-investor ref="fundFpGroupInvestor" :top-data-list="form.fundFpDetailsList" :parent-flag-show="false" @updateParentData="updateParentData" />
          <div class="tol">
            <el-button v-hasPermi="'fund:fp:edit'" size="mini" type="warning" @click="fpDistribute">{{ $t('分配') }}</el-button>
          </div>
        </div>
        <div v-if="showFpDetailsType === 'excel'">
          <el-table v-loading="excelLoading" :data="form.fundFpDetailsList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('出资人名称')" align="center" prop="investorName" min-width="180" show-overflow-tooltip />
            <el-table-column :label="$t('应分配金额') + $t('金额单位')" align="center" min-width="120" prop="totalAmount" @change="calAfterTaxFpAmount(scope.row, scope.$index)">
              <template slot-scope="scope">
                <span>{{ moneyFormat(scope.row.totalAmount, 'w') }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('税后实际分配金额') + $t('金额单位')" align="center" min-width="170">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.afterTaxFpAmount'">
                  <Money v-model="scope.row.afterTaxFpAmount" disabled :placeholder="$t('税后实际分配金额')" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('本金') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.principalCost'" :rules="fundFpDetailsListRules.principalCost">
                  <Money v-model="scope.row.principalCost" :placeholder="$t('本金')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('Hurdle') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.hurdleTheory'" :rules="fundFpDetailsListRules.hurdleTheory">
                  <Money v-model="scope.row.hurdleTheory" :placeholder="$t('Hurdle')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('追赶条款') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.chaseTerms'" :rules="fundFpDetailsListRules.chaseTerms">
                  <Money v-model="scope.row.chaseTerms" :placeholder="$t('追赶条款')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('剩余分配LP') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.surplusLp'" :rules="fundFpDetailsListRules.surplusLp">
                  <Money v-model="scope.row.surplusLp" :placeholder="$t('剩余分配LP')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('剩余分配GP') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.surplusGp'" :rules="fundFpDetailsListRules.surplusGp">
                  <Money v-model="scope.row.surplusGp" :placeholder="$t('剩余分配GP')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('股息红利') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.dividends'" :rules="fundFpDetailsListRules.dividends">
                  <Money v-model="scope.row.dividends" :placeholder="$t('股息红利')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('代扣税费') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.taxeFee'" :rules="fundFpDetailsListRules.taxeFee">
                  <Money v-model="scope.row.taxeFee" :placeholder="$t('代扣税费')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['fund:fp:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div class="tol">
            <el-button type="primary" icon="el-icon-download" size="mini" @click.native="downLoadFileOpens(fpExcelFileId)">{{ $t('下载模板') }}</el-button>
            <el-upload
              ref="uploadExcel"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="uploadExcel.headers"
              :action="uploadExcel.url"
              :disabled="uploadExcel.isUploading"
              :before-upload="handleBeforeUploadExcel"
              :on-success="handleFileSuccessExcel"
              :on-exceed="handleFileExceedExcel"
              :data="templateForm"
              class="uploadExcel"
            >
              <el-button type="primary" icon="el-icon-upload" size="mini">{{ $t('更新模板') }}</el-button>
            </el-upload>
            <el-button style="margin-left: 15px;margin-right: 5px" type="primary" icon="el-icon-check" size="mini" @click="calExcelByTemplate()">{{ $t('计算') }}</el-button>
            <el-button v-if="form.excelFileId" type="primary" icon="el-icon-download" size="mini" @click="downloadCalResult(form.excelFileId)">{{ $t('下载计算过程') }}</el-button>
          </div>
        </div>
        <div v-if="showFpDetailsType === 'manual'">
          <el-table :data="form.fundFpDetailsList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('出资人名称')" align="center" min-width="150">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('出资人名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.investorId'" :rules="fundFpDetailsListRules.investorId">
                  <el-select v-model="scope.row.investorId" :placeholder="$t('请选择')" clearable>
                    <el-option
                      v-for="dict in investorOption"
                      :key="dict.id"
                      :label="$t(dict.userName)"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('应分配金额') + $t('金额单位')" align="center" min-width="170">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.totalAmount'" :rules="fundFpDetailsListRules.totalAmount">
                  <Money v-model="scope.row.totalAmount" disabled :placeholder="$t('分配金额')" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('税后实际分配金额') + $t('金额单位')" align="center" min-width="170">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.afterTaxFpAmount'">
                  <Money v-model="scope.row.afterTaxFpAmount" disabled :placeholder="$t('税后实际分配金额')" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('本金') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.principalCost'" :rules="fundFpDetailsListRules.principalCost">
                  <Money v-model="scope.row.principalCost" :placeholder="$t('本金')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('Hurdle') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.hurdleTheory'" :rules="fundFpDetailsListRules.hurdleTheory">
                  <Money v-model="scope.row.hurdleTheory" :placeholder="$t('Hurdle')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('股息红利') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.dividends'" :rules="fundFpDetailsListRules.dividends">
                  <Money v-model="scope.row.dividends" :placeholder="$t('股息红利')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('追赶条款') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.chaseTerms'" :rules="fundFpDetailsListRules.chaseTerms">
                  <Money v-model="scope.row.chaseTerms" :placeholder="$t('追赶条款')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('剩余分配LP') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.surplusLp'" :rules="fundFpDetailsListRules.surplusLp">
                  <Money v-model="scope.row.surplusLp" :placeholder="$t('剩余分配LP')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('剩余分配GP') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.surplusGp'" :rules="fundFpDetailsListRules.surplusGp">
                  <Money v-model="scope.row.surplusGp" :placeholder="$t('剩余分配GP')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('代扣税费') + $t('金额单位')" align="center" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.taxeFee'" :rules="fundFpDetailsListRules.taxeFee">
                  <Money v-model="scope.row.taxeFee" :placeholder="$t('代扣税费')" unit="w" @change="numericalCalculation(scope.row, scope.$index)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['fund:fp:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addInvestor">{{ $t("添加") }}</el-button>
            <el-button type="primary" icon="el-icon-upload" size="mini" @click="initData()">{{ $t('导入分配详情') }}</el-button>
          </div>
        </div>
      </div>
      <!-- 附件列表 -->
      <FileTable has-permi="fund:fp" :list.sync="form.fileList" data-type="fund_fp_main" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>

    <!-- 选择回款数据来源 -->
    <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <selFundIncomeList ref="selFundIncomeList" />
    </el-dialog>

    <!-- 选择扣除费用 -->
    <el-dialog :title="'扣除费用列表'" :visible.sync="expenseOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <selFundExpenseList ref="selFundExpenseList" />
    </el-dialog>

    <div slot="footer" class="dialog-footer" style="left: 0;">
      <el-button
        v-if="(form.actStatus === 'W' || form.actStatus === 'D') && form.announcementId"
        icon="el-icon-s-promotion"
        type="success"
        @click="noticeHandle(form)"
      >{{ $t('通知详情') }}</el-button>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!-- 使用流程：保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="useProcess" ref="formBtn" :bus-data="form" has-permi="fund:callmoney" :menu-key="menuKey" :cancel-show="saveButton" :cancel-func="cancel" :save-show="saveButton" :btn-hide="btnHide" />
      <!--保存，保存并启动流程，取消 三个按钮-->
      <el-button v-if="!useProcess" @click="cancel">{{ $t('取消') }}</el-button>
      <!--  <el-button v-if="showFpDetailsType === 'auto'" v-hasPermi="'fund:fp:edit'" type="warning" @click="fpDistribute">{{ $t('分配') }}</el-button>-->
      <el-button v-if="!useProcess" v-hasPermi="'fund:fp:edit'" :disabled="!(form.id !== undefined && form.id !== null && form.id !== '') && showFpDetailsType === 'auto'" type="primary" @click="submitForm">{{ $t('保存') }}</el-button>
    </div>

    <!-- 基金分配明细对话框 -->
    <el-dialog
      :title="detailsTitle"
      :visible.sync="detailsOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogView"
      append-to-body
    >
      <fundFundFpSourceList ref="fundFundFpSourceList" />
    </el-dialog>
    <!-- 基金分配明细对话框, 根据出资人分组合计的数据 -->
    <el-dialog
      :title="detailsGroupTitle"
      :visible.sync="detailsGroupOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogView"
      append-to-body
    >
      <fund-fp-group-investor ref="fundFpGroupInvestor" />
    </el-dialog>

    <!-- 补亏项目列表对话框 -->
    <el-dialog
      :title="lossTitle"
      :visible.sync="lossOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <fundFpLossDealList ref="fundFpLossDealList" />
    </el-dialog>

    <el-dialog :title="$t('公示内容')" :visible.sync="publicityOpen" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <afficheForm v-if="publicityOpen" ref="afficheForm" :call-init-status="callInitStatus" :call-money-use-process="useProcess" :show-save-btn="form.actStatus !== 'W' && form.actStatus !== 'D'" @bindToFundCall="bindToFundCall" />
    </el-dialog>

    <el-dialog :title="$t('公告审核')" :visible.sync="emailReviewOpen" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <emailReviewForm v-if="emailReviewOpen" ref="emailReviewForm" :show-btn-status="form.actStatus !== 'W' && form.actStatus !== 'D'" />
    </el-dialog>

    <!-- 导入窗口 -->
    <el-dialog
      :title="$t('导入')"
      :visible.sync="upload.open"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <div v-loading="upload.isUploading">
        <div style="text-align: center;padding: 10px;margin-top: -10px;">
          <template>
            <el-radio v-model="tableDataDel" :label="true">{{ $t('清除现有数据') }}</el-radio>
            <el-radio v-model="tableDataDel" :label="false">{{ $t('保留现有数据') }}</el-radio>
          </template>
        </div>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :auto-upload="false"
          drag
        >
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
            <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
              {{ $t('下载模板') }}
            </el-link>
          </div>
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t(' 将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  allocationCalculate, checkFundFpQc,
  delFundFpMain,
  getFundFpMain,
  getFundLossList, getLastNewFpMainByFpTime,
  getMaxQici,
  saveFundFpMain
} from '@/api/fund/fp/fundFpMain'
import { delFundFpSource } from '@/api/fund/fp/fundFpSource'
import { delFundFpDetails, listDetailGroupInvestor } from '@/api/fund/fp/fundFpDetails'
import { listFundInvestorAll } from '@/api/fund/investor/fundInvestor'
import { getToken } from '@/utils/auth'
import { ruoyiFloat } from '@/utils/ruoyi'
import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
import { getFundBase, getFundName } from '@/api/fund/fundBase'
import { updateReviewStatus } from '@/api/fund/lpBase/lp/affiche/affiche'
import selFundIncomeList from './selFundIncomeList.vue'
import fundFundFpSourceList from './fundFundFpSourceList.vue'
import fundFpGroupInvestor from './fundFpGroupInvestor.vue'
import fundFpLossDealList from './fundFpLossDealList.vue'
import emailReviewForm from '@/views/fund/lpBase/lp/EmailReviewForm'
import afficheForm from '@/views/fund/lpBase/lp/afficheForm.vue'
import { downLoadFileOpen } from '@/utils/zipdownload'
import { excelTemplateCompute, getTemplateFileId } from '@/api/system/model/template/modelTemplate'
import selFundExpenseList from '@/views/fund/fp/selFundExpenseList.vue'
import { delFundFpExpense } from '@/api/fund/fp/fundFpExpense'
import { existBusinessId } from '@/api/fund/lpBase/lp/affiche/afficheListTemplate'

export default {
  components: {
    afficheForm,
    emailReviewForm,
    selFundIncomeList,
    selFundExpenseList,
    fundFundFpSourceList,
    fundFpGroupInvestor,
    fundFpLossDealList
  },
  data() {
    // const moneyValidCustom = (rule, value, callback) => {
    //   if (value !== undefined && value !== '' && value !== null) {
    //     const moneyMain = isNaN(this.form.fpTotalAmount) ? 0 : this.formatMoney(this.form.fpTotalAmount)
    //     var subMoney = 0
    //     this.form.fundFpDetailsList && this.form.fundFpDetailsList.forEach(item => {
    //       if (!isNaN(this.formatMoney(item.totalAmount))) {
    //         subMoney += this.formatMoney(item.totalAmount)
    //       }
    //     })
    //     console.log(this.formatMoney(subMoney).toFixed(2), this.formatMoney(moneyMain).toFixed(2))
    //     if (this.formatMoney(subMoney).toFixed(2) !== this.formatMoney(moneyMain).toFixed(2)) {
    //       if (this.showFpDetailsType !== 'auto') {
    //         callback(new Error(this.$t('出资人分配明细中, 分配金额总和与分配总金额不相等')))
    //       } else {
    //         callback()
    //       }
    //     } else {
    //       callback()
    //     }
    //   } else {
    //     callback(new Error(this.$t('必填信息')))
    //   }
    // }
    return {
      otherBtnHide: false,
      // 是否隐藏保存按钮
      btnHide: false,
      moneyEquationFlag: false,
      subFpAmount: 0,
      // 分配类型字典
      fpTypeOptions: [],
      // 表单参数
      form: {
        // 项目回款资金来源
        dealIncomeList: [],
        // 其他收益资金来源
        otherIncomeList: [],
        // 扣除费用
        fundExpenseList: []
      },
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        actTitle: [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }],
        fpQc: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }, { required: true, validator: this.checkQcReset, trigger: 'blur' }],
        fpType: [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }],
        fpTime: [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }],
        fpTotalAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }]
        // fpTotalAmount: [{ required: true, validator: this.moneyValidCustom, trigger: ['change', 'blur'] }]
      },
      fundFpDetailsListRules: {
        investorId: [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }],
        totalAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }]
      },
      templateForm: {
        templateType: 'JJFP',
        busId: this.$route.query.id
      },
      // 基金分配模板ID
      fpExcelFileId: undefined,
      // 分配计算规则Excel 上传模板
      uploadExcel: {
        // 是否显示弹出层（项目导入）
        open: false,
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken(), fundId: this.$route.query.id },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/model/modelTemplate/updateTemplate',
        // 遮罩层
        loading: false
      },
      // 查询参数
      queryParams: {
        fundId: this.$route.query.id
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      formOpen: false,
      expenseOpen: false,
      // 上次分配预留金额
      lastReserveAmount: 0,
      distributeStatus: true,
      // 查看补亏弹出层标题
      lossTitle: '',
      // 查看详情弹出层标题
      detailsTitle: '',
      // 查看详情弹出层
      detailsOpen: false,
      // 查看详情弹出层标题
      detailsGroupTitle: '',
      // 查看详情弹出层
      detailsGroupOpen: false,
      // 查看补亏列表弹出层
      lossOpen: false,
      // 基金名称
      fundName: undefined,
      loadingText: '',
      investorOption: [],
      showFpDetailsType: 'excel',
      fundFpDetailsListManual: [],
      fundFpDetailsListAuto: [],
      fundFpDetailsListExcel: [],
      // 上次计算规则，默认规则引擎计算，用于记录上次，方便不同规则之间的list赋值
      lastCalRule: 'auto',
      excelLoading: false,
      // 分配详情导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken(), fundId: this.$route.query.id, fpQc: '' },
        // headers: {},
        // 上传的地址
        url: ''
      },
      useProcess: false,
      // 基金分配计算规则字典
      fundFpCalRuleOptions: [],
      // 项目类型字典
      dealTypeOptions: [],
      typesFeeOptions: [],
      emailReviewOpen: false,
      publicityOpen: false,
      callInitStatus: true,
      tableDataDel: true,
      // 费用类型
      typeFeeOptions: [],
      saveButton: false,
      menuKey: 'fund_fp',
      url: process.env.VUE_APP_BASE_API + '/fp/fundFpDetails/analysisDetailData',
      saveBtnStatus: true
    }
  },
  watch: {
  },
  created() {
    this.$bus.$emit('async_done')
    this.getDicts('fund_fp_type').then(response => {
      this.fpTypeOptions = response.data
    })
    this.getDicts('fund_expense_type_fee').then(response => {
      this.typesFeeOptions = response.data
    })
    this.getDicts('income_source_type').then(response => {
      this.dealTypeOptions = response.data
    })
    // 基金分配计算规则字典
    this.getDicts('fund_fp_cal_rule').then(response => {
      this.fundFpCalRuleOptions = response.data
    })
    getFundName(this.$route.query.id).then(response => {
      console.log('基金数据名称', response)
      this.fundName = response
    })
    this.getDicts('fund_income_type_fee').then(response => {
      response.data.push({
        dictLabel: '项目收益',
        dictValue: 'XMSY'
      })
      this.typeFeeOptions = response.data
    })
    // 获取Excel计算规则附件模板ID
    getTemplateFileId('JJFP', this.$route.query.id).then(response => {
      this.fpExcelFileId = response.data
    })
    this.fundName = getFundName(this.$route.query.id)
    // 获取当前基金下的出资人
    listFundInvestorAll({ fundId: this.$route.query.id }).then(response => {
      this.investorOption = response.data
    })
    this.getUseProcess()
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      this.distributeStatus = true
      if (data != null && data.id !== undefined) {
        getFundFpMain(data.id).then(response => {
          this.form = response.data
          if (typeof (this.form.fpType) === 'string' && this.form.fpType !== '' && this.form.fpType !== undefined) {
            this.form.fpType = this.form.fpType.split(',')
          }
          // 判断分配明细是手动录入还是自动分配的
          this.showFpDetailsType = 'manual'
          this.lastCalRule = 'manual'
          if (this.form.fundFpDetailsList !== undefined && this.form.fundFpDetailsList !== null && this.form.fundFpDetailsList.length > 0) {
            this.form.fundFpDetailsList.some(item => {
              if (item.fpSourceId !== null && item.fpSourceId !== undefined && item.fpSourceId !== '') {
                this.showFpDetailsType = 'auto'
                this.lastCalRule = 'auto'
                return true
              }
            })
          } else {
            var _this = this
            this.showFpDetailsType = 'auto'
            this.lastCalRule = 'auto'
            this.$confirm(this.$t('该分配期次, 在上次点击系统计算进行自动分配后没有任何结果, 是否需要重新分配?'), this.$t('提示'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'info'
            }).then(function() {
              _this.submitForm('fp')
            }).then(() => {
            }).catch(function() {
            })
          }
          if (this.form.excelFileId) {
            this.showFpDetailsType = 'excel'
            this.lastCalRule = 'excel'
          }
          listDetailGroupInvestor({ fpId: this.form.id }).then(response => {
            this.total = response.total
            if (this.total > 0) {
              this.distributeStatus = false
            }
            this.loading = false
          })
          this.moneyValidCustom()
        })
      } else {
        this.reset()
        getMaxQici(this.queryParams).then(response => {
          this.form.fpQc = response.data
          this.loading = false
        })
      }
    },
    // 分配期次唯一校验
    checkQcReset(rule, value, callback) {
      if (!value) {
        return callback(new Error('必填信息'))
      } else {
        const data = {
          id: this.form.id,
          fpQc: this.form.fpQc,
          fundId: this.form.fundId
        }
        // 校验基金分配期次重复
        checkFundFpQc(data).then(res => {
          if (res.data.flag) {
            callback()
          } else {
            callback(new Error(res.data.message))
          }
        })
      }
    },
    moneyValidCustom() {
      if (this.form.fpTotalAmount !== undefined && this.form.fpTotalAmount !== '' && this.form.fpTotalAmount !== null) {
        const moneyMain = isNaN(this.form.fpTotalAmount) ? 0 : this.formatMoney(this.form.fpTotalAmount)
        var subMoney = 0
        console.log('11111111111111', this.form.fundFpDetailsList)
        if (this.form.fundFpDetailsList && this.form.fundFpDetailsList.length > 0) {
          this.form.fundFpDetailsList && this.form.fundFpDetailsList.forEach(item => {
            if (!isNaN(this.formatMoney(item.totalAmount))) {
              subMoney += this.formatMoney(item.totalAmount)
            }
          })
          console.log('22222222222')
          if (this.formatMoney(subMoney).toFixed(2) !== this.formatMoney(moneyMain).toFixed(2)) {
            this.moneyEquationFlag = true
            this.subFpAmount = this.formatMoney((this.form.fpTotalAmount - subMoney)).toFixed(2)
          } else {
            this.moneyEquationFlag = false
          }
        } else {
          this.moneyEquationFlag = false
        }
      }
    },
    typesFeeFormat(row) {
      return this.selectDictLabel(this.typesFeeOptions, row.typesFee)
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundId: this.$route.query.id,
        fpType: undefined,
        fpQc: undefined,
        fpTime: undefined,
        fpTotalAmount: undefined,
        sourceAmount: undefined,
        deductAmount: undefined,
        reserveAmount: undefined,
        excelFileId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        dealIncomeList: [],
        fundExpenseList: [],
        otherIncomeList: [],
        fundFpDetailsList: [],
        fileList: []
      }
      this.resetForm('form')
    },
    /** 新增按钮操作 */
    addHandle(dataSource, list) {
      this.formOpen = true
      this.title = this.$t('选择收益来源')
      this.$nextTick(() => {
        // this.$refs.selFundIncomeList.dataSource = dataSource
        // this.$refs.selFundIncomeList.queryParams.dataSource = dataSource
        this.$refs.selFundIncomeList.queryParams.distributionLP = 'N'
        this.$refs.selFundIncomeList.getIncomeList(list)
      })
    },
    typeFeeFormat(row) {
      return this.selectDictLabel(this.typeFeeOptions, row.fundIncome.typeFee)
    },
    /** 新增按钮操作 */
    addExpenseHandle(list) {
      this.expenseOpen = true
      this.$nextTick(() => {
        this.$refs.selFundExpenseList.getFundExpenseList(list)
      })
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 关闭form页面
      if (this.$parent.$parent.formFpOpen !== undefined) {
        this.$parent.$parent.formFpOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    // 取消按钮
    cancel() {
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formFpOpen !== undefined) {
        this.$parent.$parent.formFpOpen = false
      }
    },
    // 项目回款来源
    delRowDeal(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
        .then(function() {
          return delFundFpSource(id)
        }).then(() => {
          this.form.dealIncomeList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
        .catch(function() {
        })
      } else {
        this.form.dealIncomeList.splice(index, 1)
      }
    },
    // 其他回款来源
    delRowOther(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
        .then(function() {
          return delFundFpSource(id)
        }).then(() => {
          this.form.otherIncomeList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
        .catch(function() {
        })
      } else {
        this.form.otherIncomeList.splice(index, 1)
      }
    },
    // 其他回款来源
    delRowFundExpense(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
        .then(function() {
          return delFundFpExpense(id)
        }).then(() => {
          this.form.fundExpenseList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
        .catch(function() {
        })
      } else {
        this.form.fundExpenseList.splice(index, 1)
      }
    },
    getAllocationSum() {
      console.log('数据计算')
      this.form.fpTotalAmount = 0
      this.form.sourceAmount = 0
      this.form.deductAmount = 0
      var amountPrincipal = 0
      var amountIncome = 0
      var amountBonus = 0
      var amountOthers = 0
      this.form.dealIncomeList.forEach(income => {
        amountPrincipal = 0
        amountIncome = 0
        amountBonus = 0
        amountOthers = 0
        var item = income.fundIncome
        if (item) {
          amountPrincipal = item.amountPrincipal
          amountIncome = item.amountIncome
          amountBonus = item.amountBonus
          amountOthers = item.amountOthers
        }
        this.form.sourceAmount = this.form.sourceAmount + amountPrincipal + amountIncome + amountBonus + amountOthers
      })
      var amountMoney = 0
      this.form.fundExpenseList.forEach(fundExpense => {
        var item = fundExpense
        if (item) {
          amountMoney = item.amountMoney
        }
        this.form.deductAmount = this.form.deductAmount + amountMoney
      })
      this.form.fpTotalAmount = this.form.sourceAmount + this.formatMoney(this.lastReserveAmount) - this.formatMoney(this.form.reserveAmount) - this.form.deductAmount
    },
    // 分配预留费用 值修改对其他字段做改动
    reserveAmountCal() {
      // 本次分配金额 = 分配资金 + 上次分配预留费用 - 扣除费用 - 分配预留费用（本次）
      this.form.fpTotalAmount = this.formatMoney(this.form.sourceAmount) + this.formatMoney(this.lastReserveAmount) - this.formatMoney(this.form.reserveAmount) - this.formatMoney(this.form.deductAmount)
    },
    // 根据分配时间获取上次分配的预留费用金额，计算分配金额
    getLastFpDetail(fpTime) {
      if (fpTime === null || fpTime === undefined) {
        return
      }
      const data = {
        fpTime: fpTime,
        fundId: this.$route.query.id
      }
      getLastNewFpMainByFpTime(data).then(response => {
        if (response.data != null) {
          this.lastReserveAmount = response.data.reserveAmount
          this.form.fpTotalAmount = this.formatMoney(this.form.sourceAmount) + this.formatMoney(this.lastReserveAmount) - this.formatMoney(this.form.reserveAmount) - this.formatMoney(this.form.deductAmount)
        }
      })
    },
    // 分配计算
    fpDistribute() {
      var _this = this
      this.$confirm(this.$t('是否确认分配计算?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        _this.submitForm('fp')
      })
    },
    fpDistributeSave() {
      var _this = this
      getFundLossList(this.form.id).then(response => {
        if (response.total > 0) {
          _this.lossOpen = true
          _this.lossTitle = _this.$t('待补亏项目列表')
          _this.$nextTick(() => {
            _this.$refs.fundFpLossDealList.getFundLossDealList(this.form)
          })
          this.distributeStatus = false
        } else {
          _this.loading = true
          allocationCalculate(this.form.id).then(() => {
            _this.loading = false
            if (this.form.fundFpDetailsList === undefined || this.form.fundFpDetailsList === null || this.form.fundFpDetailsList.length <= 0) {
              this.$alert(_this.$t('本次分配没有结果! (请检查是否维护了分配规则)'), _this.$t('标题名称'), {
                confirmButtonText: _this.$t('关闭')
              })
            } else {
              _this.msgSuccess(_this.$t('分配计算成功'))
            }
            this.$refs.fundFpGroupInvestor.listDetailGroupInvestor({ id: this.form.id })
            this.distributeStatus = false
          })
        }
      }).catch(() => {
        // 如果报错了. 需要清理掉刚刚创建的分配信息
        delFundFpMain(this.form.id)
      })
    },
    /** 查看详情 */
    openDetails() {
      const row = this.form
      this.detailsGroupOpen = true
      this.detailsGroupTitle = this.$t('基金分配详情')
      this.$nextTick(() => {
        this.$refs.fundFpGroupInvestor.listDetailGroupInvestor(row)
      })
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          var flag = true
          if (type !== 'fp') {
            if (this.form.fundFpDetailsList === undefined || this.form.fundFpDetailsList === null || this.form.fundFpDetailsList.length <= 0) {
              this.msgError(this.$t('请添加出资人分配汇总数据'))
              flag = false
            }
          }
          // 如果保存的时候不是excel计算模板方式添加的出资人分配明细数据，那么把excel计算分配的过程附件id删除，避免回显的错误
          if (this.showFpDetailsType !== 'excel') {
            this.form.excelFileId = undefined
          }
          // if (flag && this.showFpDetailsType === 'manual') {
          //   var sum = 0
          //   this.form.fundFpDetailsList && this.form.fundFpDetailsList.forEach(item => {
          //     sum += Number(item.totalAmount)
          //   })
          //   if (sum !== this.form.fpTotalAmount) {
          //     flag = false
          //     this.msgError('出资人分配总和与分配总金额不相等!')
          //   }
          // }
          if (valid && flag) {
            this.loading = true
            // 目的: 不改变数据解构 , 这样对其他引用该数据的地方影响较小, 例如导入功能
            this.loadingText = this.$t('正在保存...')
            // 新增数据时 如果没有配置流程，则将审批状态设置为审批完成
            // if (!this.useProcess && !this.form.id) {
            //   this.form.actStatus = 'W'
            // }
            if (this.form.fpType !== undefined && this.form.fpType !== null && this.form.fpType !== '' && typeof (this.form.fpType) !== 'string') {
              this.form.fpType = this.form.fpType.join(',')
            }
            this.form.useProcess = this.useProcess
            saveFundFpMain(this.form).then(response => {
              if (response.code === 200) {
                this.form = response.data
                if (typeof (this.form.fpType) === 'string' && this.form.fpType !== '' && this.form.fpType !== undefined) {
                  this.form.fpType = this.form.fpType.split(',')
                }
                if (type === 'fp') {
                  this.loadingText = this.$t('正在进行分配, 请稍等...')
                  this.fpDistributeSave()
                } else if (type === 'process') {
                  if (response.data.announcementId === undefined || response.data.announcementId === null || response.data.announcementId === '') {
                    this.loading = false
                    this.$confirm(this.$t('未设置公告, 是否跳转?'), this.$t('提示'), {
                      confirmButtonText: this.$t('跳转'),
                      cancelButtonText: this.$t('取消'),
                      type: 'warning'
                    }).then(() => {
                      setTimeout(() => {
                        this.sendHandle(response.data)
                      }, 500)
                      this.startProcess(response.data)
                    }).catch(() => {
                      // 启动流程
                      this.startProcess(response.data)
                    })
                  } else {
                    // 启动流程
                    this.startProcess(response.data)
                  }
                } else {
                  this.closeForm()
                  this.loadingText = ''
                  this.loading = false
                }
                resolve(response.data.id)
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject(response)
              }
            }).catch(() => {
              this.loading = false
              reject()
            })
          } else {
            this.locationError(document)
            reject()
          }
        })
      })
    },
    // 启动流程
    startProcess: async function(data) {
      var _this = this
      var fundName = await getFundName(this.$route.query.id)
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = '「' + fundName + '」' + ' - ' + this.$t('基金分配') + ': ' + this.form.actTitle
      // 业务表名
      processData.dataTable = 'fund_fp_main'
      // 业务ID
      processData.dataId = data.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = this.useProcess ? '@/views/fund/fp/fundFpMainProcess' : '@/views/fund/fp/fundFpMainForm'
      processData.viewPath = this.useProcess ? '@/views/fund/fp/fundFpMainProcess' : '@/views/fund/fp/fundFpMainForm'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        if (_this.form.announcementId !== undefined && _this.form.announcementId !== null && _this.form.announcementId !== '') {
          updateReviewStatus(_this.form.announcementId, '待复核')
        }
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 添加一行 分配明细信息
    addInvestor() {
      var row = {
        id: undefined,
        fundId: undefined,
        fpId: undefined,
        investorId: undefined,
        dealId: undefined,
        fpTime: undefined,
        hurdleTheory: undefined,
        principalCost: undefined,
        priorityReturn: undefined,
        chaseTerms: undefined,
        balanceFp: undefined,
        taxeFee: undefined,
        totalAmount: undefined,
        afterTaxFpAmount: undefined,
        totalAmountRmb: undefined
      }
      if (!(this.form.fundFpDetailsList instanceof Array)) {
        this.$set(this.form, 'fundFpDetailsList', [])
      }
      this.$nextTick(() => {
        this.form.fundFpDetailsList.push(row)
      })
    },
    delHandle(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delFundFpDetails(id)
          }).then(() => {
          this.form.fundFpDetailsList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      } else {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          this.form.fundFpDetailsList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      }
    },
    // 如果子表是分配汇总是组件的数据.  组件中数据发生变化时. 当前一同变化
    updateParentData(data) {
      this.form.fundFpDetailsList = data
    },
    // 获取是否使用流程
    getUseProcess() {
      // 根据基金ID区分使用基金流程还是SPV流程
      getFundBase(this.$route.query.id).then(res => {
        if (res && !this.isEmpty(res.data)) {
          if (res.data.dataType === 'spv' || res.data.dataType === 'SPV') {
            this.menuKey = 'fund_fp_spv'
          }
        }
        getMenuProcess(this.menuKey).then(response => {
          this.useProcess = (response.data !== undefined && response.data !== null && response.data !== '')
        })
      })
    },
    /** 切换分配规则 */
    changeRadio(val) {
      if (val === 'auto') {
        if (this.lastCalRule === 'excel') {
          this.fundFpDetailsListExcel = this.form.fundFpDetailsList
        } else {
          this.fundFpDetailsListManual = this.form.fundFpDetailsList
        }
        this.$nextTick(() => {
          this.form.fundFpDetailsList = this.fundFpDetailsListAuto
          this.lastCalRule = val
        })
      } else if (val === 'excel') {
        if (this.lastCalRule === 'auto') {
          this.fundFpDetailsListAuto = this.form.fundFpDetailsList
        } else {
          this.fundFpDetailsListManual = this.form.fundFpDetailsList
        }
        this.$nextTick(() => {
          this.form.fundFpDetailsList = this.fundFpDetailsListExcel
          this.lastCalRule = val
        })
      } else {
        if (this.lastCalRule === 'auto') {
          this.fundFpDetailsListAuto = this.form.fundFpDetailsList
        } else {
          this.fundFpDetailsListExcel = this.form.fundFpDetailsList
        }
        this.$nextTick(() => {
          this.form.fundFpDetailsList = this.fundFpDetailsListManual
          this.lastCalRule = val
        })
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.upload.url = this.url + '?fundId=' + this.$route.query.id
      this.$nextTick(() => {
        this.$refs.upload.submit()
      })
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/detailsOfTheFundsAllocated(new)ImportTemplate.xlsx'
    },
    numericalCalculation(row, index) {
        var newVar = this.formatMoney(row.principalCost) +
        this.formatMoney(row.surplusLp) +
        this.formatMoney(row.hurdleTheory) +
        this.formatMoney(row.dividends) +
        this.formatMoney(row.chaseTerms) +
        this.formatMoney(row.surplusGp)
      this.form.fundFpDetailsList[index].totalAmount = this.formatMoney(newVar)
      console.log('11111111111')
      this.$refs['form'].validateField('fpTotalAmount', () => {})
      this.moneyValidCustom()
      this.calAfterTaxFpAmount(row, index)
    },
    // 计算税后实际分配金额（应分配金额-代扣税费）
    calAfterTaxFpAmount(row, index) {
      var newVar = this.formatMoney(row.totalAmount) - this.formatMoney(row.taxeFee)
      this.form.fundFpDetailsList[index].afterTaxFpAmount = this.formatMoney(newVar)
    },
    numericalCalculationImport(row) {
      var newVar = this.formatMoney(row.principalCost) +
        this.formatMoney(row.surplusLp) +
        this.formatMoney(row.hurdleTheory) +
        this.formatMoney(row.dividends) +
        this.formatMoney(row.chaseTerms) +
        this.formatMoney(row.surplusGp)

      return this.formatMoney(newVar)
    },
    // 导入
    initData() {
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      console.log(response)
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if (response.msg === 'success') {
        if (this.tableDataDel) {
          this.form.fundFpDetailsList = []
        }
        if (response.data !== null && response.data.length > 0) {
          response.data.forEach(item => {
            var row = {
              investorId: item.investorId,
              principalCost: item.principalCost,
              hurdleTheory: item.hurdleTheory,
              chaseTerms: item.chaseTerms,
              dividends: item.dividends,
              surplusLp: item.surplusLp,
              surplusGp: item.surplusGp,
              afterTaxFpAmount: item.afterTaxFpAmount,
              taxeFee: item.taxeFee
            }
            row.totalAmount = this.numericalCalculationImport(row)
            if (!(this.form.fundFpDetailsList instanceof Array)) {
              this.$set(this.form, 'fundFpDetailsList', [])
            }
            this.$nextTick(() => {
              this.form.fundFpDetailsList.push(row)
            })
          })
        }
        console.log(response)
        this.upload.headers.fpQc = undefined
      } else if (response.code === 500) {
        this.msgError(this.$t('数据异常'))
      } else {
        this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      }
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    },
    // 审核公告
    noticeHandle() {
      this.emailReviewOpen = true
      this.$nextTick(() => {
        this.$refs.emailReviewForm.init({ id: this.form.announcementId })
      })
    },
    // 配置公告
    sendHandle(row) {
      this.publicityOpen = true
      this.showAfficheSaveBtn = !(row.actStatus === 'W' || row.actStatus === 'D')
      this.$nextTick(() => {
        if (!this.isEmpty(row.announcementId)) {
          // 判断当前基金是否存在模板不存在取默认的
          var fundId = this.$route.query.id === undefined ? this.queryParams.fundId : this.$route.query.id
          fundId = (fundId === undefined || fundId === '' || fundId === null) ? this.form.fundId : fundId
          existBusinessId({ businessId: fundId, businessType: 'fundFpMain', orgId: '4' }).then(response => {
            if (response.data) {
              this.$refs.afficheForm.init({ id: row.announcementId, fundId: row.fundId, type: response.data.id, period: row.id, dataId: row.id })
            } else {
              this.$refs.afficheForm.init({ id: row.announcementId, fundId: row.fundId, type: '4', period: row.id, dataId: row.id })
            }
          })
        } else {
          this.updateSendHandle(row)
        }
      })
    },
    updateSendHandle(row) {
      // 判断当前基金是否存在模板不存在取默认的
      var fundId = this.$route.query.id === undefined ? this.queryParams.fundId : this.$route.query.id
      fundId = (fundId === undefined || fundId === '' || fundId === null) ? this.selectCallFundId : fundId
      existBusinessId({ businessId: fundId, businessType: 'fundFpMain', orgId: '4' }).then(response => {
        if (response.data) {
          this.$refs.afficheForm.reset()
          this.$refs.afficheForm.form.fundId = row.fundId
          this.$refs.afficheForm.form.type = response.data.id
          this.$refs.afficheForm.displayNone = { period: true, fundScale: false, callProp: false, callMoney: false }
          this.$refs.afficheForm.form.period = row.id
          this.$refs.afficheForm.form.periodTemp = row.id
          this.$refs.afficheForm.dataChange(row.fundId)
          this.$refs.afficheForm.changeType(response.data.id)
          this.$refs.afficheForm.showFpInvestor(row.id)
        }
      })
    },
    // afficheForm在首次保存并启动流程后, 跳转到通知页面进行新增, 新增完了需要把ID穿到当前表单的form.ann..Id里
    bindToFundCall(data) {
      this.form.announcementId = data.id
    },
    formatMoney(val) {
      if (val && val !== '' && !isNaN(parseFloat(val))) {
        return ruoyiFloat().formatNum(val)
      }
      return 0
    },
    // 通过Excel方式计算出资人分配明细数据
    calExcelByTemplate() {
      this.rules.fpTotalAmount = [{ required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }]
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.excelLoading = true
          this.form.fundFpDetailsList = []
          this.form.fundFpDetailsListExcel = []
          const data = {
            fundId: this.$route.query.id,
            dataId: this.form.id === undefined ? '' : this.form.id,
            busName: this.fundName,
            fpType: undefined,
            fpTotalAmount: this.form.fpTotalAmount,
            fpTime: this.form.fpTime
          }
          this.form.fundId = this.$route.query.id
          if (this.form.fpType !== undefined && this.form.fpType !== null && this.form.fpType !== '' && typeof (this.form.fpType) !== 'string') {
            data.fpType = this.form.fpType.join(',')
          }
          // 测试参数
          const param = {
            templateType: 'JJFP',
            busId: this.$route.query.id,
            paramsMap: data
          }
          excelTemplateCompute(param).then(response => {
            this.form.excelFileId = response.datas.excelFileId
            response.data.forEach(item => {
              var row = {
                investorId: item.investorId,
                type: item.type,
                investorName: item.investorName,
                principalCost: item.principalCost,
                hurdleTheory: item.hurdleTheory,
                chaseTerms: item.chaseTerms,
                afterTaxFpAmount: undefined,
                chaseTermsLp: item.chaseTermsLp,
                surplusLp: item.surplusLp,
                surplusGp: item.surplusGp,
                taxeFee: item.taxeFee
              }
              row.totalAmount = this.numericalCalculationImport(row)
              row.afterTaxFpAmount = this.formatMoney(row.totalAmount) - this.formatMoney(row.taxeFee)
              if (!(this.form.fundFpDetailsList instanceof Array)) {
                this.$set(this.form, 'fundFpDetailsList', [])
              }
              this.$nextTick(() => {
                this.form.fundFpDetailsList.push(row)
              })
            })
            this.$nextTick(() => {
              this.moneyValidCustom()
            })
            this.excelLoading = false
            // this.rules.fpTotalAmount = [{ required: true, validator: this.moneyValidCustom, trigger: ['change', 'blur'] }]
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // // 通过配置Excel-sql方式计算出资人分配明细数据
    // calExcelByTemplate() {
    //   const testData = {
    //     fundId: this.$route.query.id,
    //     fpTotalAmount: this.form.,
    //     fpTime: new Date()
    //   }
    //   // 测试参数
    //   const testParam = {
    //     templateType: 'JJFP',
    //     busId: this.$route.query.id,
    //     paramsMap: testData
    //   }
    //   excelTemplateCompute(testParam).then(response => {
    //     this.form.excelFileId = response.data.datas.excelFileId
    //     this.excelLoading = false
    //   })
    // },
    // 下载计算的结果
    downloadCalResult(fileId) {
      downLoadFileOpen(fileId)
    },
    // 下载基金分配计算模板
    downLoadFileOpens(id) {
      downLoadFileOpen(id)
    },
    // 下载系统默认基金分配计算模板
     downLoadDefaultTemplate() {
      this.downLoadExcel('/fpTemplate/fundFpTemplate/download')
    },
    // (Excel规则计算分配数据)
    handleBeforeUploadExcel(file, fileList) {
      console.log(fileList)
      // .xlsx.xls格式文件
      var flag = false
      const availableSuffixes = '.xlsx.xls'
      const suffix = file.name.substr(file.name.lastIndexOf('.') + 1, file.name.length)
      if (!availableSuffixes.includes(suffix)) {
        flag = true
      }
      if (flag) {
        this.msgError(this.$t('仅支持导入 xlsx、xls格式文件！'))
        this.$refs.uploadExcel.clearFiles()
        return false
      }
    },
    // 文件上传成功处理(Excel规则计算分配数据)
    handleFileSuccessExcel(response) {
      this.uploadExcel.open = false
      this.uploadExcel.isUploading = false
      this.$refs.uploadExcel.clearFiles()
      if (response.code === 200) {
        console.log(response.data, 'response.data')
        this.fpExcelFileId = response.data.id
        this.msgSuccess(this.$t('模板更新成功！'))
      } else if (response.code === 500) {
        this.msgError(this.$t('数据异常'))
      } else {
        this.$notify({
          title: this.$t(response.msg),
          message: '',
          type: 'success'
        })
      }
    },
    // 文件达到上限处理(Excel规则计算分配数据)
    handleFileExceedExcel() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    }

  }

}
</script>

<style lang="scss" scoped>
/deep/.uploadExcel {
  margin-left: 15px;
  display: inline-block !important;
  .el-upload-list {
    display: none;
  }
}
</style>
